package com.goldmantis.activemq.ch5;

import java.text.DecimalFormat;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer2 implements MessageListener{

    private static String brokerURL = "tcp://localhost:51616";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient Session session;
    
    private String username = "guest";
    private String password = "password";
    
    public Consumer2() throws JMSException {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection(username, password);
    	connection.setClientID("topicConsumer2");
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }    
    
    public static void main(String[] args) throws JMSException {
    	Consumer2 consumer = new Consumer2();
		Topic destination = consumer.getSession().createTopic("STOCKS.topic");
		MessageConsumer messageConsumer = consumer.getSession().createDurableSubscriber(destination, "test");
		//MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination);
		//messageConsumer.receive();
		messageConsumer.setMessageListener(consumer);
    }
	
	public void onMessage(Message message) {
		try {
			TextMessage map = (TextMessage)message;
			System.out.println("接收到message:"+map.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	public Session getSession() {
		return session;
	}

}
